import { Injectable, UnauthorizedException } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { LoginDto } from '@/dto/login.dto';
import { UsersService } from '@/services/users.service';
import { LoggingService } from '@/services/logging.service';
import * as bcrypt from 'bcrypt';

@Injectable()
export class AuthService {
    constructor(
        private readonly usersService: UsersService,
        private readonly jwtService: JwtService,
        private readonly loggingService: LoggingService,
    ) {}

    async login(loginDto: LoginDto) {
        const user = await this.validateUser(loginDto.email, loginDto.password);

        if (!user) {
            this.loggingService.app('登录失败：用户不存在或密码错误', {
                email: loginDto.email,
            });
            throw new UnauthorizedException('邮箱或密码错误');
        }

        const payload = { email: user.email, sub: user.id };
        const accessToken = this.jwtService.sign(payload);

        this.loggingService.app('用户登录成功', {
            userId: user.id,
            email: user.email,
        });

        return {
            access_token: accessToken,
            user: {
                id: user.id,
                email: user.email,
                username: user.username,
            },
        };
    }

    async validateUser(email: string, password: string): Promise<any> {
        try {
            const user = await this.usersService.findByEmail(email);
            if (user && (await bcrypt.compare(password, user.password))) {
                const { password, ...result } = user;
                return result;
            }
            return null;
        } catch (error) {
            this.loggingService.app('用户验证失败', {
                error: (error as Error).message,
            });
            return null;
        }
    }
}
